package com.linln.admin.app.service.impl;

import com.linln.admin.app.constants.AppConstants;
import com.linln.admin.app.domain.AppInfo;
import com.linln.admin.app.domain.Param;
import com.linln.admin.app.domain.RepoAccount;
import com.linln.admin.app.repository.InfoRepository;
import com.linln.admin.app.repository.RepoAccountRepository;
import com.linln.admin.app.service.InfoService;
import com.linln.admin.app.service.branch.BranchHelper;
import com.linln.common.data.PageSort;
import com.linln.common.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 陶富成
 * @date 2021/07/08
 */
@Slf4j
@Service
public class InfoServiceImpl implements InfoService {

    @Autowired
    private InfoRepository infoRepository;

    @Autowired
    private RepoAccountRepository accountRepository;

    private List<String> ignoreBranchs = Arrays.asList("head,src,master,prod,main".split(","));

    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    public AppInfo getById(Long id) {
        return infoRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     *
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<AppInfo> getPageList(Example<AppInfo> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return infoRepository.findAll(example, page);
    }

    public Page<AppInfo> getAllWithPage(int pageSize) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest(pageSize);
        return infoRepository.findAll(Example.of(new AppInfo()), page);
    }

    /**
     * 保存数据
     *
     * @param appInfo 实体对象
     */
    @Override
    public AppInfo save(AppInfo appInfo) {
        if (appInfo.getProd_line_id() == null) {
            throw new IllegalArgumentException("请选择所属产品线");
        }
        if (StringUtils.isBlank(appInfo.getBase())) {
            appInfo.setBase("prod");
        }
        //TODO 将链接中的用户名什么的都删除掉
        AppInfo info = infoRepository.save(appInfo);
        Optional<RepoAccount> ora = accountRepository.findById(info.getRepo_account_id());
        RepoAccount account = ora.isPresent() ? ora.get() : null;
        //创建prod分支
        try {
            BranchHelper.findHandler(info.getRepo_type()).createNewBranch(appInfo.getBase(), info.getRepo_url(), account.getAccount(), account.getPass(), "master", appInfo.getBase());
        } catch (Exception e) {
            if (e.toString().contains("Remote branch 'master' not found")) {
                //说明master不存在，则从main进行创建
                try {
                    BranchHelper.findHandler(info.getRepo_type()).createNewBranch(appInfo.getBase(), info.getRepo_url(), account.getAccount(), account.getPass(), "main", appInfo.getBase());
                } catch (Exception e1) {
                    log.error(e1.getMessage(), e1);
                }
            }
            log.error(e.getMessage(), e);
        }
        return info;
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        //TODO 删除时，判断一下是否有正在开发的系统在用
        return infoRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    public List<AppInfo> getAll() {
        return infoRepository.findAll();
    }

    @Override
    public List<Param> fetchAllGitBranchsByAppId(Long appId) {
        List<Param> ret = new ArrayList<>();
        try {
            if (appId == null) {
                return ret;
            }
            AppInfo app = getById(appId);
            Optional<RepoAccount> ora = accountRepository.findById(app.getRepo_account_id());
            RepoAccount account = ora.isPresent() ? ora.get() : null;
            Map<String, BranchHelper.CommitLog> branchAndCommit = BranchHelper.findHandler(AppConstants.REPO_TYPE_GIT).branchList(System.currentTimeMillis() + "", app.getRepo_url(), account.getAccount(), account.getPass());
            if (branchAndCommit == null || branchAndCommit.isEmpty()) {
                return ret;
            }
            for (String ver : branchAndCommit.keySet()) {
                if (StringUtils.isBlank(ver) || ignoreBranchs.contains(ver.trim().toLowerCase())) {
                    continue;
                }
                BranchHelper.CommitLog log = branchAndCommit.get(ver);
                if (log == null) {
                    continue;
                }
                Param p = new Param();
                p.setKey(ver);
                p.setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(log.getCommitTime()) + "(" + log.getUser() + ")");
                ret.add(p);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return ret;
    }

    @Override
    public void deleteGitBranchsByAppId(Long appId, String[] branchs) {
        try {
            if (appId == null) {
                return;
            }
            AppInfo app = getById(appId);
            Optional<RepoAccount> ora = accountRepository.findById(app.getRepo_account_id());
            RepoAccount account = ora.isPresent() ? ora.get() : null;
            for (String ver : branchs) {
                BranchHelper.findHandler(AppConstants.REPO_TYPE_GIT).deleteBranch("gitBranchDelete", app.getRepo_url(), account.getAccount(), account.getPass(), ver);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}